import React,{useState,useEffect} from 'react';
import {Table,Button,Modal,Tree} from 'antd'
import axios from '_axios@0.27.2@axios';
import { EditOutlined,DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
const Rolelist = () => {
  const [dataSource, setdataSource] = useState([])
  const [rightList, setrightList] = useState([])
  const [currentRightList, setcurrentRightList] = useState([])
  const [currentId,setcurrentId] = useState(0)
  const [isModalVisible,setisModalVisible] = useState(false)
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '操作',
      render: (item) => {
         return <div>
           <Button
             danger
             shape="circle"
             icon={<DeleteOutlined />}
             onClick={() => confirmMethod(item)}
           />
          <Button
              type="primary"
             shape="circle"
             onClick={() => {
               setisModalVisible(true)
               setcurrentRightList(item.rights)
               setcurrentId(item.id)
             }}
              icon={<EditOutlined />}
            />
       </div>
      }
    }
  ]
    // 删除提示
  const confirmMethod = (item) => {
    Modal.confirm({
    title: '删除',
    icon: <ExclamationCircleOutlined />,
    content: '你确认删除吗？',
    okText: '确认',
    cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    })
  }
    // 删除
  const deleteMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/roles/${item.id}`)
 
  }
   // 确定
  const handleOk = () => {
    setisModalVisible(false)
    setdataSource(dataSource.map(item => {
      if (item.id === currentId) {
        return {
          ...item,
          rights: currentRightList
        }
      }
      return item
    }))
     axios.patch(`/roles/${currentId}`, {
        rights:currentRightList
      })
  }
  // 取消
  const handleCancel = () => {
    setisModalVisible(false)
  }
  useEffect(() => {
    axios.get('/roles').then(res => {
      setdataSource(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get('/rights?_embed=children').then(res => {
      setrightList(res.data)
    })
  }, [])
  const onCheck = (checkKeys) => {
    setcurrentRightList(checkKeys.checked)
  }
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(item)=>item.id}
      ></Table>
       <Modal title="权限分配" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <Tree
          checkable
          onCheck = {onCheck}
          checkedKeys={currentRightList}
          checkStrictly={true}
          treeData={rightList}
          />
      </Modal>
    </div>
  );
}

export default Rolelist;
